import userTpl from '../../views/user.art'
import userListTpl from '../../views/userList.art'
import registerTpl from "../../views/register.art";
import pageHelper from '../../models/pageHelper'

export default () => {
    return (req, res, next) => {
        res.render(userTpl())
        // 将新增的模态框模板挂载DOM结点中
        $('#register').html(registerTpl())
        // 挂载新增的按钮事件
        $('#register-submit').on('click', _registerHandler())
        // 挂载用户列表, 挂载分页器, 绑定用户删除事件
        _internalPageHelper()
    }
}

const _internalPageHelper = (pageNum) => {
    pageHelper(_pageListPromise, _userRemoveEvent, pageNum)
}

const _pageListPromise = () => {
    return new Promise((resolve, reject) => {
        $.ajax({
            url: '/api/user/list',
            method: 'GET',
            success: function(result) {
                let pages = result.data.userList || []
                resolve({
                    pages,
                    id: '#user-list',
                    template: userListTpl
                })
            }
        })
    })
}

const _userRemoveEvent = () => {
    // 挂载删除用户按钮事件
    $('.user-remove-btn').on('click', function(e) {
        let user_id = $(this).attr('data-primary')
        $.ajax({
            url: '/api/user/remove',
            data: {id: user_id},
            method: 'DELETE',
            success: function(result) {
                alert(result.data.message)
                let currentPage = $('#pager ul li[class="active"]')[0].innerText
                let hasButtonCount = $('.user-remove-btn').length
                let page = hasButtonCount === 1 ? currentPage - 1 : currentPage
                _internalPageHelper(page < 1 ? 1 : page)
            }
        })
    })
}

const _registerHandler = () => {
    return (e) => {
        // 新增逻辑校验
        let $reg_usn = $('#reg-usn')
        let $reg_psw = $('#reg-psw')
        if( !$reg_usn.val() || !$reg_psw.val() ){
            alert('用户名或密码不能为空')
            return;
        }
        $.ajax({
            url: '/api/user/register',
            method: 'POST',
            data: $('#register-form').serialize(),
            success: function(result){
                if( result.status === 200 ){
                    // 模态框关闭
                    $('#register-dialog-close').click()
                    // 表单数据清空
                    $('#register-form')[0].reset()
                    // 重新加载列表
                    _internalPageHelper()
                }
                alert(result.data.message)
            }
        })
    }
}

